import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';

import Form from './components/Form';

import * as api from '@/services/blacklistDevice';
import { PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { Button, Popconfirm } from 'antd';

const List: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.BlacklistDevice | undefined>(
    undefined,
  );

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {
    const result = await api.list(params, sorter, filter);
    return Promise.resolve(result);
  };

  const handleFormSubmit = async (record: API.BlacklistDevice) => {
    let result: API.Result;
    console.log({
      ...current,
      ...record,
    });
    if (current) {
      // result = await api.update({
      //   ...current,
      //   ...record,
      // });
    } else {
      result = await api.addBlacklist({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();
    }
  };

  const handleAddWhitelist = async (id: string) => {
    const result = await api.addWhitelist({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  let columns: ProColumns<API.BlacklistDevice>[] = [
    {
      title: '设备ID',
      sorter: true,
      dataIndex: 'deviceid',
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 140,
      render: (_, record) => {
        let cmps = [];
        cmps.push(
          <Popconfirm
            key="delete"
            title="确定要将该设备加入白名单中吗?"
            onConfirm={async () => {
              await handleAddWhitelist(record.deviceid);
            }}
          >
            <a>加入白名单</a>
          </Popconfirm>,
        );
        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        cardProps={{ bodyStyle: { padding: 0 } }}
        search={{
          defaultCollapsed: false,
        }}
        style={{ border: 1 }}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        pagination={{
          defaultPageSize: 15,
          pageSizeOptions: ['15', '30', '60', '100'],
          hideOnSinglePage: true,
          // current: pageCurrent,
          // total: totalCount,
        }}
        toolBarRender={() => {
          return [
            <Button
              type="primary"
              key="create"
              onClick={() => {
                setFormVisible(true);
              }}
            >
              <PlusOutlined /> 添加设备
            </Button>,
          ];
        }}
        columns={columns}
        request={loadData}
      />
      <Form
        visible={formVisible}
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default List;
